package org.jiucheng.magpiebridge.server.aio.proxy;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;

import org.jiucheng.magpiebridge.protocol.Message;
import org.jiucheng.magpiebridge.server.aio.ServerWriteCompletionHandler;
import org.jiucheng.magpiebridge.server.aio.ServerWriteNoProxyClientReadCompletionHandler;

/**
 * 
 * @author jiucheng
 *
 */
public class ProxyReadCompletionHandler implements CompletionHandler<Integer, ProxyAttachment> {
    
    public void completed(Integer result, ProxyAttachment attachment) {
        if (result == -1) {
            try {
                attachment.getAsynchronousSocketChannel().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (attachment.getServerAttachment().canWrited()) {
                Message proxym = new Message();
                proxym.setMagic(Message.MAGIC);
                proxym.setType(Message.Type.DISCONNECT);
                proxym.setUri(attachment.getUri());
                ByteBuffer writeBuffer = Message.toByteBuffer(proxym);
                
                attachment.getServerAttachment().getServer().write(writeBuffer, attachment.getServerAttachment().setWriteBuffer(writeBuffer), new ServerWriteNoProxyClientReadCompletionHandler());
                return;
            }
        }
        
        if (attachment.getServerAttachment().canWrited()) {
            ByteBuffer readByteBuffer = attachment.getReadBuffer();
            readByteBuffer.flip();
            Message message = new Message();
            message.setMagic(Message.MAGIC);
            message.setType(Message.Type.TRANSFER);
            message.setUri(attachment.getUri());
            byte[] bts = new byte[result];
            readByteBuffer.get(bts);
            message.setData(bts);
            message.setSize(bts.length);
            ByteBuffer writeBuffer = Message.toByteBuffer(message);
            
        	attachment.getServerAttachment().getServer().write(writeBuffer, attachment.getServerAttachment().setWriteBuffer(writeBuffer), new ServerWriteCompletionHandler());
        }
    }
    
    public void failed(Throwable exc, ProxyAttachment attachment) {
        if (attachment.getServerAttachment().canWrited()) {
            Message proxym = new Message();
            proxym.setMagic(Message.MAGIC);
            proxym.setType(Message.Type.DISCONNECT);
            proxym.setUri(attachment.getUri());
            ByteBuffer writeBuffer = Message.toByteBuffer(proxym);
            
            attachment.getServerAttachment().getServer().write(writeBuffer, attachment.getServerAttachment().setWriteBuffer(writeBuffer), new ServerWriteNoProxyClientReadCompletionHandler());
            return;
        }
        exc.printStackTrace();
    }
}
